import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import utils.ClusterDistanceCalculator;

import data.ClusteredNode;
import data.Gene;

public class Clustor {

	private Gene[] genes;
	private ClusterDistanceCalculator calculator;
	private int numberOfClusters = 1;

	public Clustor() {
	}

	public boolean setNumberOfClusters(int n) {
		if (n > 0) {
			numberOfClusters = n;
		}
		return (n > 0);
	}

	public List<ClusteredNode> getClusters() {
		List<ClusteredNode> clusters = new ArrayList<ClusteredNode>(genes.length);

		for (int i = 0; i < genes.length; i++) {
			ClusteredNode c = new ClusteredNode();
			c.add(genes[i]);
			clusters.add(c);
		}

		while (clusters.size() > numberOfClusters) {
			ClusteredNode c1 = null;
			ClusteredNode c2 = null;
			double min = Double.MAX_VALUE;

			for (ClusteredNode ci : clusters) {
				for (ClusteredNode cj : clusters) {
					if (ci == cj) {
						continue;
					}
					double distance = calculator.distance(ci, cj);
					if (min > distance) {
						c1 = ci;
						c2 = cj;
						min = distance;
					}
				}
			}

			ClusteredNode merged = new ClusteredNode();
			merged.add(c1);
			merged.add(c2);

			clusters.remove(c1);
			clusters.remove(c2);
			clusters.add(merged);
		}
		return clusters;
	}

	public void setGenes(Gene[] genes) {
		this.genes = genes;
	}

	public void setCalculator(ClusterDistanceCalculator calculator) {
		this.calculator = calculator;
	}
}
